package com.starryx.blog.dao;

import com.starryx.blog.po.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface BlogRepository extends
        JpaRepository<Blog, Long>,          // 基本类
        JpaSpecificationExecutor<Blog> {    // 特殊查询类，类似于实现动态sql查询

    // 查询前几个推荐的博客
    @Query("select b from Blog b where b.recommend = true")
    List<Blog> findTop(Pageable pageable);

    // 根据关键词查询
    /*
    *    ?1 : 表示方法中的第一个参数
    */
    @Query("select b from Blog b where b.title like ?1 or b.content like ?1")
    Page<Blog> findByQuery(String query, Pageable pageable);

    @Modifying      // 标识为修改语句
    @Query("update Blog b set b.views = b.views+1 where b.id = ?1")
    int updateViews(Long id);           // 更新操作是返回 int 类型的

    // 查询所有博客的年份列表
    @Query("select function('date_format', b.updateTime, '%Y') as year from Blog b group by function('date_format', b.updateTime, '%Y') order by year desc ")
    List<String> findGroupYear();

    // 根据年份查询
    @Query("select b from Blog b where function('date_format', b.updateTime, '%Y') = ?1")
    List<Blog> findByYear(String year);
}
